package com.xinchuang.fiter;

import com.alibaba.fastjson.JSONObject;
import com.xinchuang.TargetManageRun;
import com.xinchuang.util.RedisUtil;
import com.xinchuang.utils.MyUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Enumeration;

/**
 * @author zhangxuan
 * @Description TODO 登录验证
 * @Date 17:35 2020/12/30
 * @Param
 * @return
 **/
@Slf4j
public class AuthenticationInterceptor implements HandlerInterceptor {

    private static String REQUEST_WAY = "OPTIONS";

    @Autowired
    private RedisUtil redisUtil;

    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,
                             Object object) throws Exception {
        if (!TargetManageRun.isInit) {
            // 返回特定内容
            httpServletResponse.setContentType("application/json");
            httpServletResponse.setCharacterEncoding("UTF-8");
            // 构造JSON字符串
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("code", 500);
            jsonObject.put("message", "系统初始化中，请稍后");
            jsonObject.put("data", null);
            httpServletResponse.getWriter().write(jsonObject.toJSONString());
            httpServletResponse.setStatus(HttpServletResponse.SC_OK);
            // 终止请求继续处理
            return false;
        }
        log.info("请求路径：" + httpServletRequest.getRequestURI());

        String method = httpServletRequest.getMethod();
        System.out.println("请求方式：" + httpServletRequest.getMethod());
        if (method.equals(REQUEST_WAY)) {
            return true;
        }
        String id = httpServletRequest.getHeader("Id");
        log.info("用户ID：" + id);
        if (StringUtils.isBlank(id)) {
            // 返回特定内容
            httpServletResponse.setContentType("application/json");
            httpServletResponse.setCharacterEncoding("UTF-8");
            // 构造JSON字符串
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("code", 500);
            jsonObject.put("message", "用户不存在，请重新登陆");
            jsonObject.put("data", null);
            // 设置状态码为403禁止访问
            httpServletResponse.getWriter().write(jsonObject.toJSONString());
            httpServletResponse.setStatus(HttpServletResponse.SC_OK);
            // 终止请求继续处理
            return false;
        }
        if (!redisUtil.hasKey("USER_KUNMING_USERID_" + id)) {
            // 返回特定内容
            httpServletResponse.setContentType("application/json");
            httpServletResponse.setCharacterEncoding("UTF-8");
            // 构造JSON字符串
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("code", 500);
            jsonObject.put("message", "用户不存在，请重新登陆");
            jsonObject.put("data", null);
            // 设置状态码为403禁止访问
            httpServletResponse.getWriter().write(jsonObject.toJSONString());
            httpServletResponse.setStatus(HttpServletResponse.SC_OK);
            // 终止请求继续处理
            return false;
        }
        Object userId = redisUtil.get("USER_KUNMING_USERID_" + id);
        Object digestHex = redisUtil.get("USER_KUNMING_ENCRYPT_" + userId);
        if (!digestHex.toString().equals(id)) {
            // 返回特定内容
            httpServletResponse.setContentType("application/json");
            httpServletResponse.setCharacterEncoding("UTF-8");
            // 构造JSON字符串
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("code", 401);
            jsonObject.put("message", "用户已在其他地方登录");
            jsonObject.put("data", null);
            // 设置状态码为403禁止访问
            httpServletResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            httpServletResponse.getWriter().write(jsonObject.toJSONString());
            // 终止请求继续处理
            return false;
        }
        httpServletResponse.setHeader("userId", userId.toString());
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o,
                           ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,
                                Object o, Exception e) throws Exception {
    }

}
